package cn.player.act.frag;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONObject;

import java.util.List;

import cn.player.App;
import cn.player.R;
import cn.player.adapter.RightChannelInfoAdapter;
import cn.player.entity.ChannelInfo;
import cntv.player.engine.Const;
import cn.player.media.entity.VideoInfo;
import cn.player.media.fragment.MediaPlayFragment;
import cn.player.media.util.ParseUtil;

public class ChannelInfoFragment extends ListFragment {

    private App app;
    private FinalHttp finalHttp;
    private Context mContext;
    private String recomUrl;
    protected List<ChannelInfo> mChannelInfos;
    protected RightChannelInfoAdapter mChannelInfoAdapter;
    private MediaPlayFragment mMediaFrag;


    public static ChannelInfoFragment newInstance(String recomUrl) {
        ChannelInfoFragment rFrag = new ChannelInfoFragment();
        Bundle args = new Bundle();
        args.putString("recomUrl", recomUrl);
        rFrag.setArguments(args);
        return rFrag;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        app = (App) mContext.getApplicationContext();
        finalHttp = app.getFinalHttp();
        recomUrl = getArguments().getString("recomUrl");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (mMediaFrag == null) {
            mMediaFrag = (MediaPlayFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.ll_play_area);
        }
        getListView().setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                switch (scrollState) {
                    case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                    case OnScrollListener.SCROLL_STATE_IDLE:
                        mMediaFrag.getMediaController().show();
                        break;
                    case OnScrollListener.SCROLL_STATE_FLING:
                        break;

                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub

            }
        });

        if (mChannelInfos != null && mChannelInfos.size() > 0) {
            mChannelInfoAdapter = new RightChannelInfoAdapter(mContext, mChannelInfos, R.layout.right_channel_item_view);
            setListAdapter(mChannelInfoAdapter);
        } else {
            finalHttp.get(recomUrl, new AjaxCallBack<String>() {
                @Override
                public void onStart() {
                    // TODO Auto-generated method stub
                    super.onStart();
                }

                @Override
                public void onSuccess(String t) {
                    // TODO Auto-generated method stub
                    super.onSuccess(t);
                    try {

                        JSONObject response = new JSONObject(t);
                        mChannelInfos = ParseUtil.parseDataToCollection(response.optJSONObject("data"), "items", ChannelInfo.class);
                        mChannelInfoAdapter = new RightChannelInfoAdapter(mContext, mChannelInfos, R.layout.right_channel_item_view);
                        setListAdapter(mChannelInfoAdapter);

                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    // TODO Auto-generated method stub
                    super.onFailure(t, errorNo, strMsg);
                }

            });
        }

    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Log.i("zl", "Item clicked: " + id);
        VideoInfo videoInfo = convertToLiveVideoInfo(mChannelInfos.get(position));
//        reAddPlayer(videoInfo);

        mMediaFrag.playVideo(videoInfo);
    }


    /**
     * 重新添加播放器
     */
    private void reAddPlayer(VideoInfo videoInfo) {
        FragmentManager fragMgr = getActivity().getSupportFragmentManager();
        FragmentTransaction fragTran = fragMgr.beginTransaction();
        fragTran.detach(mMediaFrag);
        mMediaFrag.setVideoInfo(videoInfo);
        fragTran.attach(mMediaFrag);
//		MediaPlayFragment mpFrag = MediaPlayFragment.newInstance(videoInfo);
//		fragTran.replace(R.id.ll_play_area, mpFrag);
        fragTran.commit();
    }

    /**
     * 将ChannelInfo转换为直播VideoInfo
     *
     * @param channelInfo
     * @return
     */
    private VideoInfo convertToLiveVideoInfo(ChannelInfo channelInfo) {
        VideoInfo vInfo = new VideoInfo();
        vInfo.setFlag(Const.LIVE);
        vInfo.setTitle(channelInfo.getTitle());
        vInfo.setDetailUrl(channelInfo.getLiveUrl());
        vInfo.setChannelId(channelInfo.getChannelId());
        vInfo.setP2pUrl(channelInfo.getP2pUrl());
//		vInfo.setShareUrl(channelInfo.getShareUrl());
        vInfo.setRate(Const.PLAYER_MODE_HD);
        vInfo.setTimeShift(true);
        vInfo.setOrder(channelInfo.getOrder());

        return vInfo;
    }


    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Log.i("zl", "ChannelInfoFragment onStart");
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.i("zl", "ChannelInfoFragment onResume");
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.i("zl", "ChannelInfoFragment onPause");
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Log.i("zl", "ChannelInfoFragment onStop");
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        Log.i("zl", "ChannelInfoFragment onDestroyView");
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.i("zl", "ChannelInfoFragment onDestroy");

    }

    @Override
    public void onDetach() {
        // TODO Auto-generated method stub
        super.onDetach();
        Log.i("zl", "ChannelInfoFragment onDetach");
    }
}
